package com.at.abc.r420_ak;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.ArrayDeque;
import java.util.Arrays;

public class d {

    static BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
    static PrintWriter out = new PrintWriter(System.out);

    public static void main(String[] args) throws IOException {
        solve();
        out.flush();
        out.close();
        br.close();
    }

    static void solve() throws IOException {
        String[] in = br.readLine().split(" ");
        h = Integer.parseInt(in[0]);
        w = Integer.parseInt(in[1]);
        grid = new char[h][w];
        int si = -1, sj = -1, gi = -1, gj = -1;
        for (int i = 0; i < h; i++) {
            grid[i] = br.readLine().toCharArray();
            for (int j = 0; j < w; j++) {
                if (grid[i][j] == 'S') {
                    si = i;
                    sj = j;
                } else if (grid[i][j] == 'G') {
                    gi = i;
                    gj = j;
                }
            }
        }
        int ans = bfs(si, sj, gi, gj);
        if (ans == Integer.MAX_VALUE / 4) out.println(-1);
        else out.println(ans);

    }

    static int h, w;
    static char[][] grid;


    public static int bfs(int si, int sj, int gi, int gj) {
        final int ans = Integer.MAX_VALUE / 4;
        int[][][] dist = new int[h][w][2];
        for (int i = 0; i < h; i++) {
            for (int j = 0; j < w; j++) {
                Arrays.fill(dist[i][j], ans);
            }
        }
        ArrayDeque<int[]> q = new ArrayDeque<>();
        dist[si][sj][0] = 0;
        q.add(new int[]{si, sj, 0});

        int[] di = {-1, 1, 0, 0};
        int[] dj = {0, 0, -1, 1};

        while (!q.isEmpty()) {
            int[] cur = q.poll();
            // f == 0 : o 为open，x 为 close
            // f == 1 : o 为close，x 为 open
            int ci = cur[0], cj = cur[1], f = cur[2];
            int cd = dist[ci][cj][f];

            if (ci == gi && cj == gj) return cd;

            for (int k = 0; k < 4; k++) {
                int ni = ci + di[k], nj = cj + dj[k];
                if (ni < 0 || ni >= h || nj < 0 || nj >= w) continue;
                char ch = grid[ni][nj];
                if (ch == '#') continue;

                if ((f == 0 && ch == 'x') || (f == 1 && ch == 'o')) continue;

                int nf = f;
                if (ch == '?') nf = 1 - f;

                if (dist[ni][nj][nf] > cd + 1) {
                    dist[ni][nj][nf] = cd + 1;
                    q.add(new int[]{ni, nj, nf});
                }
            }
        }

        return ans;
    }
}
